package com.shishi.fast.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 类描述：JwtToken生成的工具类
 * JWT token的格式：header.payload.signature
 * header的格式（算法、token的类型）：
 * {"alg": "HS512","typ": "JWT"}
 * payload的格式（用户名、创建时间、生成时间）：
 * {"sub":"wang","created":1489079981393,"exp":1489684781}
 * signature的生成算法：
 * HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
 * Created by liuhaifeng on 2022/3/17.
 */
@Slf4j
@Component
public class JwtTokenUtil {

    private static final String CLAIM_KEY_CREATED = "created";

    private static final String TOKEN_HEAD = "Bearer";// JWT负载中拿到开头
    private static final long EXPIRATION = 2592000;//JWT的超期限时间30天(60*60*24*30)
    private static final String TOKEN_HEADER = "Authorization";//JWT存储的请求头
    private static final String SECRET = "shuanghu-shishi-kfhbj32hfm";//JWT加解密使用的密钥


    /**
     * 根据HttpServletRequest 获取 token
     */
    private static String getTokenFormRequest(HttpServletRequest request) {
        return request.getHeader(TOKEN_HEADER);
    }

    /**
     * 根据用户信息生成token
     */
    public static String generateToken(String userId, String phone, String username, String companyId, boolean isSuperAdmin) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("phone", phone);
        claims.put("username", username);
        claims.put("companyId", companyId);
        claims.put("isSuperAdmin", isSuperAdmin);
        claims.put(CLAIM_KEY_CREATED, new Date());

        return generateToken(claims);
    }

    /**
     * 从token中获取登录用户id
     */
    public static String getUserId(HttpServletRequest request) {
        String userId;
        try {
            String token = getTokenFormRequest(request);
            Claims claims = getClaimsFromToken(token);
            userId = claims.get("userId", String.class);
        } catch (Exception e) {
            userId = null;
        }
        return userId;
    }

    /**
     * 从token中获取登录用户账号
     */
    public static String getUserPhone(HttpServletRequest request) {
        String userPhone;
        try {
            String token = getTokenFormRequest(request);
            Claims claims = getClaimsFromToken(token);
            userPhone = claims.get("phone", String.class);
        } catch (Exception e) {
            userPhone = null;
        }
        return userPhone;
    }

    /**
     * 从token中获取登录用户名称
     */
    public static String getUsername(HttpServletRequest request) {
        String username;
        try {
            String token = getTokenFormRequest(request);
            Claims claims = getClaimsFromToken(token);
            username = claims.get("username", String.class);
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 从token中获取登录用户企业id
     */
    public static String getCompanyId(HttpServletRequest request) {
        String companyId;
        try {
            String token = getTokenFormRequest(request);
            Claims claims = getClaimsFromToken(token);
            companyId = claims.get("companyId", String.class);
        } catch (Exception e) {
            companyId = null;
        }
        return companyId;
    }

    /**
     * 从token中判断登录用户是否是超级管理员
     */
    public static boolean boolUserIsSuperAdmin(HttpServletRequest request) {
        boolean isSuperAdmin;
        try {
            String token = getTokenFormRequest(request);
            Claims claims = getClaimsFromToken(token);
            isSuperAdmin = claims.get("isSuperAdmin", Boolean.class);
        } catch (Exception e) {
            return false;
        }
        return isSuperAdmin;
    }

    /**
     * 根据负责生成JWT的token
     */
    private static String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    private static Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}", token);
        }
        return claims;
    }

    /**
     * 生成token的过期时间
     */
    private static Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + EXPIRATION * 1000);
    }

    /**
     * 验证token是否还有效
     *
     * @param request 客户端传入的request
     */
    public static boolean validateToken(HttpServletRequest request) {
        try {
            String token = getTokenFormRequest(request);
            return !isTokenExpired(token);
        } catch (Exception ex) {
            return false;
        }
    }

    /**
     * 判断token是否已经失效
     */
    private static boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    private static Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 当原来的token没过期时是可以刷新的
     *
     * @param oldToken 带tokenHead的token
     */
    public String refreshHeadToken(String oldToken) {
        if (StringUtils.isBlank(oldToken)) {
            return null;
        }
        String token = oldToken.substring(TOKEN_HEAD.length());
        if (StringUtils.isBlank(token)) {
            return null;
        }
        //token校验不通过
        Claims claims = getClaimsFromToken(token);
        if (claims == null) {
            return null;
        }
        //如果token已经过期，不支持刷新
        if (isTokenExpired(token)) {
            return null;
        }
        //如果token在30分钟之内刚刷新过，返回原token
        if (tokenRefreshJustBefore(token, 30 * 60)) {
            return token;
        } else {
            claims.put("CLAIM_KEY_CREATED", new Date());
            return generateToken(claims);
        }
    }

    /**
     * 判断token在指定时间内是否刚刚刷新过
     *
     * @param token 原token
     * @param time  指定时间（秒）
     */
    private boolean tokenRefreshJustBefore(String token, int time) {
        Claims claims = getClaimsFromToken(token);
        Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
        Date refreshDate = new Date();
        //刷新时间在创建时间的指定时间内
        if (refreshDate.after(created) && refreshDate.before(DateUtils.addSeconds(created, time))) {
            return true;
        }
        return false;
    }
}
